package Dao.Impl;

import Dao.LikeDAO;
import utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author Su
 * @Date 2025/5/1 10:42
 * @Version 1.0 （版本号）
 */
public class LikeDAOImpl implements LikeDAO {
    private Connection connection;

    public LikeDAOImpl(Connection connection) {
        this.connection = connection;
    }

    //check 是否点过赞
    @Override
    public boolean hasLiked(int articleId, int userId) throws SQLException {
        String sql =  "SELECT * FROM article_likes WHERE article_id = ? AND user_id = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)){
            pstmt.setInt(1, articleId);
            pstmt.setInt(2, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                return rs.next() && rs.getInt("status") == 1;
            }
        } catch (SQLException e) {
            System.out.println("执行异常");
            return false; // 明确处理异常情况
        }
    }


    //统计有效点赞数
    @Override
    public Integer getLikeCounts(int articleId) throws SQLException {
        String sql =  "SELECT count(*) as like_count FROM article_likes WHERE article_id = ? AND status = 1";
        // try-with-resources自动关闭PreparedStatement
        try (PreparedStatement pstmt = connection.prepareStatement(sql)){
            pstmt.setInt(1, articleId);

            // 执行查询，并用try-with-resources自动关闭ResultSet
            try (ResultSet rs = pstmt.executeQuery()) {
                // 如果有查询结果，返回统计值；否则返回0 三元
                return rs.next() ? rs.getInt("like_count") : 0;
            }
        } catch (SQLException e) {
            System.out.println("执行异常");
            return 0; // 明确处理异常情况
        }
    }
}
